package com.zrq.jwtdemo.author.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrq.jwtdemo.author.dto.request.UsersRequest;
import com.zrq.jwtdemo.author.dto.result.UsersListResult;
import com.zrq.jwtdemo.author.mapper.UsersMapper;
import com.zrq.jwtdemo.author.model.Users;
import com.zrq.jwtdemo.core.constant.Constant;
import com.zrq.jwtdemo.core.exception.AppException;
import com.zrq.jwtdemo.core.prop.JwtProp;
import com.zrq.jwtdemo.core.utils.JwtUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;

/**
* <p>
    * 用户表 服务类
    * </p>
*
* @author zrq
* @since 2020-12-20
*/
@Service
@AllArgsConstructor
@Validated
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class IUsersService {

    private final UsersMapper iUsersMapper;

    private final JwtProp jwtProp;

    private final JwtUtils jwtUtils;

    private final ModelMapper modelMapper;


    @Transactional(readOnly = true)
    public List<UsersListResult> getUserList(HttpServletRequest request) {
        String token = request.getHeader(jwtProp.getHeader());
        Integer userId = jwtUtils.getUserId(token);
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .ne(Users::getId,userId)
                .isNull(Users::getDeletedAt);
        List<Users> users = iUsersMapper.selectList(queryWrapper);
        List<UsersListResult> listResults = users.stream().map(f -> {
            UsersListResult result = modelMapper.map(f, UsersListResult.class);
            if (result.getSex().equals("0")) {
                result.setSex("男");
            } else {
                result.setSex("女");
            }
            if (result.getStatus().equals("0")) {
                result.setStatus("禁用");
            } else {
                result.setStatus("启用");
            }
            return result;
        }).collect(Collectors.toList());
        return listResults;
    }

    @Transactional(readOnly = false)
    public void insUser(UsersRequest request) {

        byte[] encode = Base64.getEncoder().encode(request.getPassword().getBytes());
        Users users = modelMapper.map(request, Users.class);
        users.setStatus(1);
        //加密
        users.setPassword(new String(encode, StandardCharsets.UTF_8));
        if (iUsersMapper.insert(users) < 0)
            throw new AppException("添加用户失败");
    }
}
